package itsm.isperp.framework.ldap.synchronize;

import itsm.isperp.framework.ldap.LdapContextUtils;
import itsm.isperp.framework.security.encoding.DESHelper;
import itsm.isperp.module.entity.app.AppUser;

import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-9-7
 * @since 1.0
 * 
 */
public class UserSync {

	protected final static Log logger = LogFactory.getLog(UserSync.class);

	public static List<AppUser> readSystemUserData(String dc,
			String customerUserOU, String customerId, LdapContext ctx)
			throws NamingException {
		List<AppUser> list = new ArrayList<>();

		String searchBase = LdapContextUtils.getDomainControllerOU(dc,
				customerUserOU);
		String searchFilter = LdapContextUtils.USER;

		// 搜索控制器
		SearchControls searchCtls = new SearchControls();
		// 创建搜索控制器
		searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		String returnedAtts[] = { "primaryGroupID", "employeeID", "name", "cn",
				"userPrincipalName", "physicalDeliveryOfficeName",
				"telephoneNumber", "mobile", "company", "department", "title",
				"physicalDeliveryOfficeName", "distinguishedName",
				"sAMAccountName", "whenChanged", "mail", "memberOf",
				"Pwd-Last-Set", "User-Password", "userAccountControl" }; // 定制返回属性
		// 映射关系
		// primaryGroupID所在组
		// name,cn 姓名
		// userPrincipalName 域登录用户名 如CK@ad.local
		// departmentNumber
		// telephoneNumber 电话
		// mobile 手机
		// company 公司,department 部门,title 职务
		// physicalDeliveryOfficeName 地址
		// distinguishedName 例子： CN=陈科CK,OU=计算机中心,OU=广汽三菱供应商,DC=ad,DC=local
		// sAMAccountName 域帐号名 如CK
		// whenChanged 最后修改日期
		// mail 邮箱
		// memberOf 隶属于

		searchCtls.setReturningAttributes(returnedAtts);
		NamingEnumeration<SearchResult> answer = ctx.search(searchBase,
				searchFilter, searchCtls);
		while (answer.hasMoreElements()) {// 遍历结果集
			SearchResult sr = (SearchResult) answer.next();
			String dn = sr.getName();
			logger.info("ad->dn：" + dn);
			Attributes attrs = sr.getAttributes();
			if (attrs != null) {
				Attribute attrName = attrs.get("name");
				// Attribute userPrincipalName = attrs.get("userPrincipalName");
				Attribute telephoneNumber = attrs.get("telephoneNumber");
				Attribute mobile = attrs.get("mobile");
				Attribute company = attrs.get("company");
				// /Attribute department = attrs.get("department");
				Attribute title = attrs.get("title");
				Attribute physicalDeliveryOfficeName = attrs
						.get("physicalDeliveryOfficeName");
				Attribute distinguishedName = attrs.get("distinguishedName");
				Attribute sAMAccountName = attrs.get("sAMAccountName");
				Attribute mail = attrs.get("mail");
				String d = UnitSync.getUnitPath((String) distinguishedName
						.get());

				AppUser u = new AppUser();

				Attribute userAccountControlAtr = attrs
						.get("userAccountControl");

				u.setEnable(true);
				if (userAccountControlAtr != null) {
					int ua = Integer.parseInt(userAccountControlAtr.get()
							.toString());

					int dis = ua & 2;

					if (dis == 2) {
						u.setEnable(false);
					}
				}

				u.setAddress(physicalDeliveryOfficeName == null ? null
						: (String) physicalDeliveryOfficeName.get());
				u.setAppDepartmentId("u" + d.hashCode());
				u.setCompany(company == null ? null : (String) company.get());
				u.setEmail(mail == null ? null : (String) mail.get());

				u.setFullname((String) attrName.get());
				u.setId((String) sAMAccountName.get());
				u.setMobile(mobile == null ? null : (String) mobile.get());
				u.setName(u.getId());
				u.setTel(telephoneNumber == null ? null
						: (String) telephoneNumber.get());
				u.setPosition(title == null ? null : (String) title.get());
				u.setPassword(DESHelper.getDefualEncryptPassword());
				list.add(u);

			}
		}
		return list;
	}
 
}
